package com.uduemc.biso.web.controller;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.uduemc.biso.core.utils.RedisUtil;

@Controller
public class IndexController {

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private RedisUtil redisUtil;

	@GetMapping("/")
	public String index() {

		return "index";
	}

	/**
	 * 会员登录地
	 * 
	 * @return
	 */
	@GetMapping("/login")
	public String login(@RequestParam(value = "error", required = false) String error,
			@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "time", required = false) String time, Model model, Locale locale) {

		error = StringUtils.trimAllWhitespace(error);
		username = StringUtils.trimAllWhitespace(username);

		model.addAttribute("username", username);
		if (StringUtils.hasText(error)) {
			// 判断是否执行过
			boolean hasKey = redisUtil.hasKey(error + username);
			if (hasKey) {
				String token = (String) redisUtil.get(error + username);
				if (!time.equals(token)) {
					try {
						model.addAttribute("error", messageSource.getMessage("login.exception." + error, null, locale));
					} catch (NoSuchMessageException e) {
					}
				}
			}else {
				try {
					model.addAttribute("error", messageSource.getMessage("login.exception." + error, null, locale));
				} catch (NoSuchMessageException e) {
				}
			}
			redisUtil.set(error + username, time, 120);
		}
		return "login";
	}
}
